package com.study.scapp.info.common;

import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author 1
 * @data 2023/5/14
 */
@RestController
@RequestMapping("/common")
public class UploadCommon {

    private String path;

    //文件上传
    @PostMapping("/file/upload")
    public String file(@RequestParam("file") MultipartFile file){
        try {
            System.out.println(file.getOriginalFilename());//文件名
            System.out.println(file.getContentType());//文件类型
            System.out.println(file.getSize());//文件大小
            System.out.println(file.getInputStream());//文件的输入流

            //获得文件上传的路径；
            String path = ResourceUtils.getURL("classpath:").getPath()+"/static/files";

            System.out.println(path);
            File newFile=new File(path);//由于自定义的实体类和java.io.File重名
            //文件夹不存在则重建
            if(!newFile.exists()){
                newFile.mkdirs();
            }
            //上传
            String fileName=file.getOriginalFilename();
            File file1 = new File(newFile, fileName);
            file.transferTo(new File(newFile,fileName));
            //将文件上传的url存入数据表中
            System.out.println("文件上传成功");
            file.getInputStream().close();
            String path1 = file1.getPath();
            return path1;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }



}
